<?php

namespace App\Http\Controllers;

use App\Models\Org;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

class OrgController extends Controller
{
    public function __construct(Request $request)
    {
        if (preg_match('#^api/org/term#', $request->path())
            || preg_match('#^api/changchun/info#', $request->path())
        ) {
            parent::__construct();
            return;
        }

        $user = $request->user();

        if (!$user || $user->type != 4 && $user->type != 5) {
            throw new \Exception('权限不足');
        }

        parent::__construct();
    }

    public function index(Request $request)
    {
        $perPage = $request->get('perPage', 10);
        $builder = Org::query();

        if ($request->has('name')) {
            $builder->where('name', 'like', '%'.$request->get('name').'%');
        }

        $user = $request->user();
        $info = [];
        if ($user->type == 5) {
            $org_list = $user->platform->org_list;
            $builder = $builder->whereIn('id', $org_list);
            $info['data'] = $builder->get()->toArray();
            $info['total'] = count($org_list);
        } else {
            $info = $builder->paginate($perPage)->toArray();
        }

        $ids = array_map(function($item) {
            return $item['id'];
        }, $info['data']);

        $teams = DB::table('team')
            ->select(DB::raw('count(*) as team_count, org_id'))
            ->where('verify_status', '=', 1)
            ->where('in_blacklist', '=', 0)
            ->whereIn('org_id', $ids)
            ->groupBy('org_id')
            ->get();

        $teamMap = [];
        foreach ($teams as $team) {
            $teamMap[$team->org_id] = $team;
        }


        $projects = DB::table('project')
            ->select(DB::raw('count(*) as project_count, org_id'))
            ->where('verify_status', '=', '1')
            ->whereIn('org_id', $ids)
            ->groupBy('org_id')
            ->get();

        $projectMap = [];
        foreach ($projects as $project) {
            $projectMap[$project->org_id] = $project;
        }

        $volunteers = DB::table('volunteer')
            ->select(DB::raw('count(*) as volunteer_count, org_id'))
            ->whereIn('org_id', $ids)
            ->groupBy('org_id')
            ->get();

        $volunteerMap = [];
        foreach ($volunteers as $volunteer) {
            $volunteerMap[$volunteer->org_id] = $volunteer;
        }

        $rewards = DB::table('volunteer')
            ->select(DB::raw('sum(reward_time) as reward_count, org_id'))
            ->whereIn('org_id', $ids)
            ->groupBy('org_id')
            ->get();

        $rewardMap = [];
        foreach ($rewards as $reward) {
            $rewardMap[$reward->org_id] = $reward;
        }

        foreach ($info['data'] as &$item) {
            if (isset($teamMap[$item['id']])) {
                $item['team_count'] = $teamMap[$item['id']]->team_count;
            } else {
                $item['team_count'] = 0;
            }

            if (isset($projectMap[$item['id']])) {
                $item['project_count'] = $projectMap[$item['id']]->project_count;
            } else {
                $item['project_count'] = 0;
            }

            if (isset($volunteerMap[$item['id']])) {
                $item['volunteer_count'] = $volunteerMap[$item['id']]->volunteer_count;
            } else {
                $item['volunteer_count'] = 0;
            }

            if (isset($rewardMap[$item['id']])) {
                $item['reward_count'] = $rewardMap[$item['id']]->reward_count;
            } else {
                $item['reward_count'] = 0;
            }
        }

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function show($id)
    {
        $node = Org::findOrFail($id);
        $data = $node->toArray();

        if (isset($data['user_id'])) {
            $user = User::findOrFail($data['user_id']);
            $data['username'] = $user->username;
            $data['email'] = $user->email;
        }

        $data['modules'] = $data['module_settings'];
        unset($data['module_settings']);

        return $this->returnJSON($data, 0, 'ok');
    }


    public function store(Request $request) {
        $this->validate($request, [
            'name' => 'required|max:32|unique:org,name',
            'type' => 'required|max:32',
            'contact_name' => 'required|max:32',
            'contact_phone' => 'required|max:32',
            'contact_email' => 'required|max:255|email',
            'address' => 'required',
            'corporate_name' => 'required|max:32',
            'corporate_id' => 'required|max:32',
            'corporate_phone' => 'required|max:32',
            'username' => 'required|unique:user|max:64',
            'pwd' => 'required|max:64'
        ]);

        $node = new Org();
        $data = $request->only([
            'name',
            'type',
            'logo',
            'contact_name',
            'contact_phone',
            'contact_email',
            'address',
            'corporate_name',
            'corporate_id',
            'corporate_phone',
            'quality',
            'username',
            'pwd',
            'email'
        ]);

        // default values;
        $data['user_id'] = 0;
        $data['business_licence'] = isset($data['business_licence']) ? $data['business_licence'] : '';
        $data['logo'] = isset($data['logo']) ? $data['logo'] : '';
        $data['quality'] = isset($data['quality']) ? $data['quality'] : '';
        $data['module_settings'] = [];
        $data['wechat_app_id'] = isset($data['wechat_app_id']) ? $data['wechat_app_id'] : '';
        $data['wechat_app_secret'] = isset($data['wechat_app_secret']) ? $data['wechat_app_secret'] : '';
        $data['wechat_verify_file'] = isset($data['wechat_verify_file']) ? $data['wechat_verify_file'] : '';
        $data['cert_title'] = isset($data['cert_title']) ? $data['cert_title'] : '';
        $data['cert_org'] = isset($data['cert_org']) ? $data['cert_org'] : '';
        $data['cert_cachet'] = isset($data['cert_cachet']) ? $data['cert_cachet'] : '';
        $data['cert_auth_org'] = isset($data['cert_auth_org']) ? $data['cert_auth_org'] : '';
        $data['duiba_key'] = isset($data['duiba_key']) ? $data['duiba_key'] : '';
        $data['duiba_secret'] = isset($data['duiba_secret']) ? $data['duiba_secret'] : '';
        $data['score_settings'] = isset($data['score_settings']) ? $data['score_settings'] : '';
        $data['org_info'] = isset($data['org_info']) ? $data['org_info'] : '';
        $data['org_manual'] = isset($data['org_manual']) ? $data['org_manual'] : '';
        $data['org_service'] = isset($data['org_service']) ? $data['org_service'] : '';
        $data['org_service_tel'] = isset($data['org_service_tel']) ? $data['org_service_tel'] : '';

        $node->fill($data);

        if ($node->save()) {

            if (isset($data['pwd'])) {
                $user = new User();
                $user->fill([
                    'username' => $data['username'],
                    'pwd' => bcrypt($data['pwd']),
                    'email' => isset($data['email']) ? $data['email'] : '',
                    'type' => 3,
                    'org_id' => $node->id
                ]);
                $user->save();
                $node->fill([
                    'user_id' => $user->id
                ]);
                $node->save();
            }

            return $this->returnJSON(null, 0, '新增成功');
        }
        return $this->returnJSON(null, 500, '新建失败');
    }

    public function update(Request $request, $id)
    {
        $node = Org::findOrFail($id);

        $this->validate($request, [
            'name' => ['required', 'max:32', Rule::unique('org')->ignore($id)],
            'type' => 'required|max:32',
            'contact_name' => 'required|max:32',
            'contact_phone' => 'required|max:32',
            'contact_email' => 'required|max:255|email',
            'address' => 'required',
            'corporate_name' => 'required|max:32',
            'corporate_id' => 'required|max:32',
            'corporate_phone' => 'required|max:32',
            'username' => [
                'max:64',
                Rule::unique('user')->ignore($node->user_id)
            ],
            'pwd' => 'max:64'
        ]);

        $data = $request->only([
            'name',
            'type',
            'logo',
            'contact_name',
            'contact_phone',
            'contact_email',
            'address',
            'corporate_name',
            'corporate_id',
            'corporate_phone',
            'quality',
            'username',
            'pwd',
            'email'
        ]);

        $data = $this->rmNullProps($data);

        // default values;
        //$data['business_licence'] = isset($data['business_licence']) ? $data['business_licence'] : '';
        //$data['logo'] = isset($data['logo']) ? $data['logo'] : '';
        //$data['quality'] = isset($data['quality']) ? $data['quality'] : '';
        //$data['wechat_app_id'] = isset($data['wechat_app_id']) ? $data['wechat_app_id'] : '';
        //$data['wechat_app_secret'] = isset($data['wechat_app_secret']) ? $data['wechat_app_secret'] : '';
        //$data['wechat_verify_file'] = isset($data['wechat_verify_file']) ? $data['wechat_verify_file'] : '';
        //$data['cert_title'] = isset($data['cert_title']) ? $data['cert_title'] : '';
        //$data['cert_org'] = isset($data['cert_org']) ? $data['cert_org'] : '';
        //$data['cert_cachet'] = isset($data['cert_cachet']) ? $data['cert_cachet'] : '';
        //$data['cert_auth_org'] = isset($data['cert_auth_org']) ? $data['cert_auth_org'] : '';
        //$data['duiba_key'] = isset($data['duiba_key']) ? $data['duiba_key'] : '';
        //$data['duiba_secret'] = isset($data['duiba_secret']) ? $data['duiba_secret'] : '';
        //$data['score_settings'] = isset($data['score_settings']) ? $data['score_settings'] : '';
        //$data['org_info'] = isset($data['org_info']) ? $data['org_info'] : '';
        //$data['org_manual'] = isset($data['org_manual']) ? $data['org_manual'] : '';
        //$data['org_service'] = isset($data['org_service']) ? $data['org_service'] : '';
        //$data['org_service_tel'] = isset($data['org_service_tel']) ? $data['org_service_tel'] : '';


        if (isset($data['pwd'])) {
            if ($node->user_id) {
                $user = User::findOrFail($node->user_id);
                $user->fill([
                    'username' => $data['username'],
                    'pwd' => bcrypt($data['pwd']),
                    'email' => isset($data['email']) ? $data['email'] : '',
                ]);
                $user->save();
            } else {
                $user = new User();
                $user->fill([
                    'username' => $data['username'],
                    'pwd' => bcrypt($data['pwd']),
                    'email' => isset($data['email']) ? $data['email'] : '',
                    'type' => 3,
                    'org_id' => $node->id
                ]);
                $user->save();
                $data['user_id'] = $user->id;
            }
        }


        $node->fill($data);
        if ($node->save()) {
            return $this->returnJSON(null, 0, '保存成功');
        }
        return $this->returnJSON(null, 500, '保存失败');
    }

    public function destroy(Request $request, $id)
    {
        throw new \Exception('不允许删除');

        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        if (Org::whereRaw('id IN (?)', [$ids])->delete()) {
            User::whereIn('org_id', $ids)->delete();

            // todo 删除所有子团队，子团队账号，子项目。。。

            return $this->returnJSON($ids, 0, '删除成功');
        } else {
            return $this->returnJSON(null, 1, "删除失败");
        }
    }



    public function online(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = Org::whereIn('id',  $ids)->update(['in_blacklist' => 0]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '启用成功');
        } else {
            return $this->returnJSON(null, 1, "启用失败");
        }
    }
    public function offline(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = Org::whereIn('id',  $ids)->update(['in_blacklist' => 1]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '禁用成功');
        } else {
            return $this->returnJSON(null, 1, "禁用失败");
        }
    }

    public function sug(Request $request, $term = '') {

        $builder = Org::query()->select('name', 'id');

        if (strlen($term)) {
            $builder->where('name', 'like', '%'.$term.'%');
        }

        $nodes = $builder->get()->toArray();

        // 不储存在options里
        if ($request->has('not_options')) {
            return $this->returnJSON(
                array_map(function($node) {
                    return [
                        'value' => $node['id'],
                        'label' => $node['name']
                    ];
                }, $nodes)
            );
        }

        // 储存在options里
        return $this->returnJSON([
            'options' => array_map(function($node) {
                return [
                    'value' => $node['id'],
                    'label' => $node['name']
                ];
            }, $nodes)
        ]);
    }

    public function saveSettings(Request $request, $id) {
        $user = $request->user();

        if (!($user->type === 5 || $user->type === 4 || $user->type === 3 && $user->org_id == $id)) {
            throw new \Exception('权限不足');
        }

        $node = Org::findOrFail($id);

        $data = $request->only([
            'modules',
            'wechat_app_id',
            'wechat_app_secret',
            'wechat_verify_file',
            'wechat_payment_merchant_id',
            'wechat_payment_key',

            'cert_title',
            'cert_org',
            'cert_cachet',
            'cert_auth_org',

            'duiba_key',
            'duiba_secret',
            'score_settings',
            'score_name',

            'org_info',
            'org_manual',
            'org_service',
            'org_service_tel',

//            'real_name_register',
            'org_service_guide',
        ]);
        $data = $this->rmNullProps($data);

        if (isset($data['modules'])) {
            $data['module_settings'] = $data['modules'];
            unset($data['modules']);
        }

        if ((isset($data['duiba_key']) || isset($data['duiba_secret'])) && empty($data['score_settings'])) {
            $data['score_settings'] = [
                'register' => '10',
                'certification' => '10',
                'reward_time' => '10',
                'project_hire' => '5',
            ];
        }

        $node->fill($data);
        if($node->save()){
            return $this->returnJSON($node->toArray(), 0, '保存机构设置成功');
        }
        return $this->returnJSON(null, 0, '操作失败');
    }

    public function changChun(){
        $teamIds = DB::table('team')->select('id')
            ->where('org_id', 33)
            ->get()->toArray();
        $volunteers = DB::table('volunteer')
            ->where('org_id', 33)
            ->count();

        $projects = DB::table('project')
            ->where('org_id', 33)->where('verify_status', '=', '1')
            ->count();
        return $this->returnJSON([
            'registerCount' => $volunteers,
            'teamCount' => count($teamIds),
            'activityCount' => $projects,
        ], 0, '');
    }

    public function getWechatSettings(Request $request, $id)
    {
        $user = $request->user();

        if (!($user->type === 5 || $user->type === 4 || $user->type === 3 && $user->org_id == $id)) {
            throw new \Exception('权限不足');
        }

        $node = Org::findOrFail($id);
        return $this->returnJSON($node->wechat_message_config, 0, '');

    }
    public function saveWechatSettings(Request $request, $id)
    {
        $user = $request->user();

        if (!($user->type === 5 || $user->type === 4 || $user->type === 3 && $user->org_id == $id)) {
            throw new \Exception('权限不足');
        }

        $node = Org::findOrFail($id);

        $data = $request->only([
            'apply_project_vol',
            'join_team_vol',
            'sign_on_vol',
            'reward_time_vol',
            'reward_time_patch_vol',
            'station_letter_vol',
            'project_attention_vol',

            'apply_project_team',
            'sign_on_team',
            'reward_time_patch_team',
            'project_verify_team',
            'station_letter_team',
            'join_team',
        ]);


        $data['wechat_message_config'] = [
            'apply_project_vol' => $data['apply_project_vol'],
            'join_team_vol' => $data['join_team_vol'],
            'sign_on_vol' => $data['sign_on_vol'],
            'reward_time_vol' => $data['reward_time_vol'],
            'reward_time_patch_vol' => $data['reward_time_patch_vol'],
            'station_letter_vol' => $data['station_letter_vol'],
            'project_attention_vol' => $data['project_attention_vol'],

            'apply_project_team' => $data['apply_project_team'],
            'sign_on_team' => $data['sign_on_team'],
            'reward_time_patch_team' => $data['reward_time_patch_team'],
            'project_verify_team' => $data['project_verify_team'],
            'station_letter_team' => $data['station_letter_team'],
            'join_team' => $data['join_team'],
        ];

        $node->fill(['wechat_message_config' => $data['wechat_message_config']]);
        if ($node->save()) {
            return $this->returnJSON($node->toArray(), 0, '保存机构设置成功');
        }
        return $this->returnJSON(null, 0, '操作失败');
    }
}
